package interface_layer;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import processing_layer.SessionTracker;
import processing_layer.User;

import database_layer.Common;
import database_layer.QueryDispatcher;
import database_layer.UpdateDispatcher;

/**
 * This servlet is in charge of removing a user from the web service.
 * It is triggered after a request from an admin to delete the user.
 */
public class RemoveUser extends HttpServlet
{
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RemoveUser()
    {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
	{
		try
		{
			String username = (String) request.getSession().getAttribute("username");
			String userType = (String) request.getSession().getAttribute("userType");
			
			if (null == username || null == userType)
			{
				ErrorHandler.parseForErrors(Common.UNAUTHORIZED_OPERATION, response, null);
				return;
			}
			
			if (!userType.equals(Common.adminType))
			{
				ErrorHandler.parseForErrors(Common.UNAUTHORIZED_OPERATION, response, null);
				return;
			}
			
			String userToRemove = request.getParameter("userToRemove");
			
			if (null == userToRemove)
			{
				ErrorHandler.parseForErrors(Common.BAD_PARAMETERS, response, null);
				return;
			}
			
			if (SessionTracker.isAlreadyConnected(userToRemove))
			{
				ErrorHandler.parseForErrors(Common.USER_CONNECTED, response, null);
				return;
			}
	
			User userToRemoveDetails = QueryDispatcher.getUserDetails(userToRemove);
			if (null == userToRemoveDetails)
			{
				ErrorHandler.parseForErrors(Common.INTERNAL_DB_ERROR, response, null);
				return;
			}
			
			if (null == userToRemoveDetails.username)
			{
				ErrorHandler.parseForErrors(Common.ENTRY_DOESNT_EXIST, response, null);
				return;
			}
				
			int returnValue = UpdateDispatcher.removeUser(userToRemove);
			ErrorHandler.parseForErrors(returnValue, response, "allUsers.jsp");
		}
		catch (Exception e)
		{
			System.out.println("Exception is : " + e.getLocalizedMessage());
			ErrorHandler.parseForErrors(Common.INTERNAL_ERROR, response, null);
		}
	}


}
